package com.cxyzy.filedemo

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        writeFileBtn.setOnClickListener {
            checkPermissionAndWriteFile()
        }
        readFileBtn.setOnClickListener {
            checkPermissionAndReadFile()
        }
    }

    /**
     * 检查权限并写文件
     */
    private fun checkPermissionAndWriteFile() {
        runWithPermissions(Permission.WRITE_EXTERNAL_STORAGE) {
            writeFile("test data")
        }
    }

    /**
     * 写文件
     */
    private fun writeFile(data: String) {
        val testFile = getTestFile()
        getTestFile().writeText(data)
        Toast.makeText(this, "filePath:${testFile.absolutePath}", Toast.LENGTH_SHORT).show()
    }

    /**
     * 检查权限并写文件
     */
    private fun checkPermissionAndReadFile() {
        runWithPermissions(Permission.WRITE_EXTERNAL_STORAGE) {
            readFile()
        }
    }

    /**
     * 读文件
     */
    private fun readFile() {
        val testFile = getTestFile()
        val content = testFile.readText()
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
    }

    private fun getTestFile(): File {
        val dir = File(getExternalFilesDir(null)?.absolutePath, "tmp")
        dir.mkdirs()

        return File(dir.absolutePath + "/test.txt")
    }
}
